import { createRouter, createWebHistory } from 'vue-router'
import { useCounterStore } from '../stores/counter'
import Home from '../views/Home.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
      children:[
      ]
    },
    {
      path:'/login',  
      name:'Login',
      component:()=>import('../views/Login.vue')
    },  
    {
      path:'/createOrder',
      name:'CreateOrder',
      component:()=>import('../views/CreateOrder.vue')
    },{
      path:'/toPay',
      name:'ToPay',
      component:()=>import('../views/ToPay.vue')
    },{
      path:'/paySuccess',
      name:'PaySuccess',
      component:()=>import('../views/PaySuccess.vue')
    },
    {
      path:'/address',
      name:'Address',
      component:()=>import('../views/Address.vue')
    },{
      path:'/editorAddAdress',
      name:'EditorAddAdress',
      component:()=>import('../views/EditorAddAdress.vue')
    },{
      path:'/order',
      name:'Order',
      component:()=>import('../views/Order.vue')
    },{
      path:'/user',
      name:'User',
      component:()=>import('../views/User.vue')
    },{
      path:'/register',
      name:'Register',
      component:()=>import('../views/Register.vue')
    }

  ]
})

// 所有的路由在真正被访问到之前(解析渲染对应组件页面前),都会先经过全局前置守卫
// 只有全局前置守卫放行了,才会到达对应的页面

// 全局前置导航守卫
// to:到哪里去,到哪去的完整路由信息对象(路径，参数)
// from:从哪里来, 从哪来的完整路由信息对象(路径，参数)
// next:是否放行
// (1) next() 直接放行,放行到to要去的路径
// (2) next(路径) 进行拦截,拦截到next里面配置的路径

// 定义一个数组,专门用于用户存放所有非权限访问的页面
const authUrls = ['/login','/register']
router.beforeEach((to, from, next) => {
   // console.log(to, from, next)
  // 看to.path是否在authUrls中出现过
  if (authUrls.includes(to.path)) {
    // 非权限页面,直接放行
    console.log('非权限页面,直接放行')
    next()
    return
  } 
  // 是权限页面,需要判断token
  const token = useCounterStore().token
  if (token) {
    console.log('放行'+token)
    next()
  } else {
    console.log('拦截')
    next('/login')
  }
})

export default router
